import os
import json
import pandas as pd
import os
from utils import log_info, log_error

def convert_json_to_excel(json_path, excel_path):
    log_info(f"开始将 {json_path} 转换为 {excel_path}")
    try:
        # 读取JSON文件
        with open(json_path, 'r', encoding='utf-8') as f:
            questions = json.load(f)
            if not isinstance(questions, list):
                raise ValueError("JSON文件格式不正确，应为JSON数组")
            if len(questions) == 0:
                raise ValueError("JSON文件为空")

        # 移除id字段
        for q in questions:
            if 'id' in q:
                del q['id']

        # 创建DataFrame
        df = pd.DataFrame(questions)

        # 保存为Excel文件
        df.to_excel(excel_path, index=False, engine='openpyxl')

        log_info(f"成功将 {json_path} 转换为 {excel_path}")
        log_info(f"共转换 {len(questions)} 条记录")
        return True

    except Exception as e:
        log_error(f"转换过程中出错: {str(e)}")
        return False

if __name__ == "__main__":
    # 设置文件路径
    json_path = os.path.join("data", "tk.json")
    excel_path = os.path.join("data", "tk_excel.xlsx")

    # 执行转换
    convert_json_to_excel(json_path, excel_path)